package com.hongbo.widget.test_messenger

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger

class SayService : Service() {

    override fun onBind(intent: Intent): IBinder {
        return messenger.binder
    }

    private val messenger: Messenger = Messenger(
        @SuppressLint("HandlerLeak") object : Handler() {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    Constants.MSG_TYPE_SAY -> {
                        val clientMsg: String = msg.data.getString(Constants.MSG_KEY_DATA) ?: ""
                        val resMsg = Message.obtain(msg)
                        resMsg.data = Bundle().apply {
                            putString(
                                Constants.MSG_KEY_DATA,
                                "这里是aihongbo进程，接收到消息：${clientMsg}"
                            )
                        }
                        msg.replyTo.send(resMsg)
                    }
                }
                super.handleMessage(msg)
            }
        })
}